import { FriendMessageEntity } from './../../entities/friendMessage.entity';
import { FriendEntity } from './../../entities/friend.entity';
import { Injectable, HttpException } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class FriendService {
  constructor(
    @InjectRepository(FriendEntity)
    private readonly friendRepository: Repository<FriendEntity>,
    @InjectRepository(FriendMessageEntity)
    private readonly friendMessageRepository: Repository<FriendMessageEntity>,
  ) {}

  async getFriends(userId: string) {
    const friendList = await this.friendRepository.find({ user_id: userId });
    return friendList;
  }

  async getFriendMessages(userId: string, friendId: string) {
    try {
      let data = [];
      const sendMessage = await this.friendMessageRepository.find({user_id: userId, friend_id: friendId});
      const receiveMessage = await this.friendMessageRepository.find({user_id: friendId, friend_id: userId});
      data = [...sendMessage, ...receiveMessage];
      data.sort((a: any, b: any) => {
        return a.create_at - b.create_at;
      });
      return data;
    } catch(e) {
      console.log(e);
      // return HttpException
    }
  }
}
